
import 'package:flutter/material.dart';
import 'package:yp/helper.dart';
import 'package:yp/services/api.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:sp_util/sp_util.dart';

import 'state.dart';

class SignInLogic extends GetxController {
  final state = SignInState();

  @override
  void onInit() {
    super.onInit();
    // 获取积分
    var paramsIntegral = {
      'access_token':  SpUtil.getString('token'),
    };
    Api.userIntegral(paramsIntegral).listen((event) {
      if (event['code'] == 0) {
        state.integralStr = event['point'].toString();
      }
      update();
    });

    var rulesParams = {
      'access_token': SpUtil.getString('token'),
      'page': 1,
      'page_size': 10,
    };
    Api.signInRules(rulesParams).listen((event) {
      print('签到规则 返回数据  成功  event = $event');
      if (event['code'] == 0) {
        List list = event['sign_in_rule_infos'];
        if (list.length > 0) {
          state.signInRulesString = list[0]['remark'];
          state.ruleNumIdStr = list[0]['rule_num_id'].toString();
          var params = {
            'access_token': SpUtil.getString('token'),
            'rule_num_id': list[0]['rule_num_id'],
          };
          Api.estimateSignInReward(params).listen((event) {
            print('预估用户未来七天签到奖励  成功  event = $event');
            if (event['code'] == 0) {
              List signInList = event['sign_in_recodes'];
              if (signInList.length > 0) {
                state.nextSevenDays = signInList;
              }
            }
            update();
          }, onError: (error) {
            print('预估用户未来七天签到奖励  失败  error = $error');
          });

          var params1 = {
            'access_token': SpUtil.getString('token'),
            'rule_num_id': list[0]['rule_num_id'],
            'usr_num_id': SpUtil.getInt('empeNumId'),
          };
          Api.continuitySignInDays(params1).listen((event) {
            print(' 连续签到天数 成功 ================  event = $event');
            if (event['code'] == 0) {
              state.continuitySignInDaysStr = event['total_sign_in_day_count']?.toString() ?? '0';
            }
            update();
          }, onError: (error) {
            print(' 连续签到天数 失败 ================  error = $error');
          });
        }
      }
      update();
    }, onError: (error) {
      print('签到规则 返回数据  失败  error = $error');
    });

  }

  void signInClick(BuildContext context) {
    var params = {
      'access_token': SpUtil.getString('token'),
      'usr_num_id': SpUtil.getInt('empeNumId'),
      // 'channel_num_id': state.ruleNumIdStr,
      'channel_num_id': 99,
      // 'sign_date': '2021-09-27 14:57:00',
      'sign_date': '${DateFormat("yyyy-MM-dd HH:mm:ss").format(DateTime.now())}',
    };
    print('++++++++++++    params = $params');
    Api.signIn(params).listen((event) {
      state.isSignIn = false;
      print('签到成功 返回数据   event = $event');
      if (event['code'] == 0) {
        showDialog(
          context: context,
          useSafeArea: false,
          builder: (context) {
            return Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                  width: setWidth(540),
                  height: setWidth(380),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(setWidth(24)),
                    gradient: LinearGradient(
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                      colors: [
                        Color(0xffFDF0D9),
                        Color(0xffffffff),
                      ],
                    ),
                  ),
                  child: Stack(
                    children: [
                      Container(
                        width: setWidth(540),
                        height: setWidth(380),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(setWidth(24)),
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Padding(
                              padding: EdgeInsets.only(
                                top: setWidth(36),
                                bottom: setWidth(16),
                              ),
                              child: Text(
                                '签到成功！',
                                style: TextStyle(
                                  color: Color(0xff805321),
                                  fontSize: 20,
                                  decoration: TextDecoration.none,
                                ),
                              ),
                            ),
                            Container(
                              width: setWidth(144),
                              height: setWidth(144),
                              decoration: BoxDecoration(
                                color: Colors.yellow,
                                borderRadius: BorderRadius.circular(setWidth(72)),
                              ),
                              alignment: Alignment.center,
                              child: Text(
                                '+' + event['reward_integral'].toString(),
                                textAlign: TextAlign.center,
                                style: TextStyle(
                                  color: Color(0xff805321),
                                  fontSize: 20,
                                  decoration: TextDecoration.none,
                                ),
                              ),
                            ),
                            SizedBox(
                              height: setWidth(40),
                            ),
                            Text(
                              '恭喜获得${event['reward_integral'].toString()}个积分～',
                              style: TextStyle(
                                color: Color(0xff999999),
                                fontSize: 14,
                                decoration: TextDecoration.none,
                              ),
                            ),
                          ],
                        ),
                      ),
                      // Positioned(
                      //   top: 0,
                      //   right: 0,
                      //   child: InkWell(
                      //     onTap: () {
                      //       print('！！！删除弹框 点击事件！！！');
                      //       Navigator.pop(context);
                      //     },
                      //     child: Container(
                      //       padding: EdgeInsets.symmetric(horizontal: setWidth(28), vertical: setWidth(24)),
                      //       child: Image.asset(
                      //         'assets/images/close_images.png',
                      //         width: setWidth(26),
                      //         height: setWidth(26),
                      //         color: Color(0xff979797),
                      //         fit: BoxFit.cover,
                      //       ),
                      //     ),
                      //   ),
                      // ),
                    ],
                  ),
                ),
                SizedBox(
                  height: setWidth(60),
                ),
              ],
            );
          },
        );
        onInit();
        // state.continuitySignInDaysStr = '${int.parse(state.continuitySignInDaysStr) + 1}';
        // state.integralStr = '${event['reward_integral'] + double.parse(state.integralStr)}';
      } else {
        toast('签到失败！');
      }
      update();
    }, onError: (error) {
      state.isSignIn = false;
      toast('签到失败！');
      print('签到失败 返回数据   error = $error');
    });
  }

}